import Search from "antd/es/input/Search";
import "./style.less";
import { DeleteOutlined } from "@ant-design/icons";
import type { CollapseProps } from "antd";
import { Collapse, Modal } from "antd";
import useCategory from "@/hooks/useCategory";
import { useState } from "react";
import { deleteCategory, addCategory } from "@/utils/back/index";

function Category() {
  // 新增分类
  const [inputValue, setInputValue] = useState("");
  const onAddCategory = (e: string) => {
    if (e == "") return;
    console.log("e", e);
    addCategory({ name: e }).then(() => {
      // 更新数据
      setInputValue("");
      refresh();
    });
  };

  // 分类展示
  const { categoriesWithArticles, refresh } = useCategory();

  // 删除分类
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [modalText, setModalText] = useState("确认删除分类及文章吗？");
  const [categoriesId, setCategoriesId] = useState(0);

  const showModal = () => {
    setOpen(true);
  };
  // 确认删除
  const handleOk = () => {
    setModalText("The modal will be closed after two seconds");
    setConfirmLoading(true);
    deleteCategory(categoriesId)
      .then(() => {
        setOpen(false);
        setConfirmLoading(false);
        // 更新数据
        refresh();
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const handleCancel = () => {
    setOpen(false);
  };
  // 点击删除图标
  const genExtra = (id: number) => {
    return (
      <DeleteOutlined
        style={{ fontSize: "23px" }}
        onClick={(event) => {
          setCategoriesId(id); // 设置要删除的分类ID
          console.log("点击删除图标", categoriesId);
          showModal(); // 显示模态框
          event.stopPropagation();
        }}
      />
    );
  };

  const arr: any = [];
  categoriesWithArticles.forEach((item: any) => {
    const obj = {
      key: item.categoriesId,
      label: item.categoryName,
      children: item.articles.map((e: any) => {
        return <div className="articleItem">{e}</div>;
      }),
      extra: genExtra(item.categoriesId),
    };

    arr.push(obj);
  });

  const items: CollapseProps["items"] = arr;

  return (
    <div className="categoryManagement">
      <Search
        placeholder="input text"
        allowClear
        enterButton="新增"
        size="large"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        onSearch={(e) => onAddCategory(e)}
      />
      <Collapse defaultActiveKey={["1"]} accordion items={items} />
      <Modal
        title="提示"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <p>{modalText}</p>
      </Modal>
    </div>
  );
}
export default Category;
